package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.joda.time.MutableDateTime;

import com.conversationboard.cache.newanswers.NewAnswersThread;
import com.conversationboard.model.Board;
import com.conversationboard.model.Boards;
import com.conversationboard.model.User;

@WebServlet(name = "NewAnswersOnDateControllerServlet", urlPatterns = "/NewAnswersOnDateControllerServlet")
public class NewAnswersOnDateControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 7198370556004040505L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {

			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");

			int weeksAgo = 0;
			boolean weeksAgoSearch = false;

			int boardId = Integer.parseInt(request.getParameter("boardid"));
			Board board = Boards.getBoard(boardId);
			User user = User.get(request.getUserPrincipal().getName());

			if (board.isPrivateBoard() && (!user.isMemberOfBoard(boardId))) {
				return;
			}

			if (request.getParameter("weeksago") != null) {
				weeksAgo = Integer.parseInt(request.getParameter("weeksago"));
				weeksAgoSearch = true;
			}

			List<NewAnswersThread> threads;

			if (weeksAgoSearch) {

				/* If we want a date range */

				MutableDateTime endDate = new MutableDateTime();
				endDate.addDays(1); /* Make it the end of today */
				int numberOfDays = 7;

				if (weeksAgo > 0) {
					endDate.addWeeks(-weeksAgo);
				}

				threads = board.getNewAnswersForDateRange(endDate.toDate(), numberOfDays);

			} else {

				/* If we want a specific date */

				String dateString = request.getParameter("date");

				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
				Date date = formatter.parse(dateString);

				threads = board.getNewAnswersForDate(date);
			}

			request.setAttribute("threads", threads);
			request.setAttribute("board", board);
			request.setAttribute("user", user);

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/newanswers.jsp");
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		} catch (NumberFormatException e) {
		} catch (ParseException e) {
			throw new ServletException(e);
		}

	}

}
